package cn.zhouyang.redistest.push;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @Author:ZhouYang
 * @Description:
 * @Date: Created in 2021/3/23 9:03
 * @Modified By：订阅频道
 */
public class SubThread  extends Thread{

    private final JedisPool jedisPool;
    private final Subscriber subscriber = new Subscriber();
    private final String channel = "myChannel";

    public SubThread(JedisPool jedisPool) {
        super("SubThread");
        this.jedisPool = jedisPool;
    }

    @Override
    public void run() {
        System.out.println(String.format("subscribe redis, channel %s, thread will be blocked", channel));
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //通过subscribe 的api去订阅，入参是订阅者和频道名
            jedis.subscribe(subscriber,channel);
        }catch (Exception e){
            System.out.println(String.format("subsrcibe channel error, %s", e));
        }finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }
}
